package com.apexsoft.monitor.front.console.app.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apexsoft.front.common.support.Result;
import com.apexsoft.monitor.common.MonitorConstant;
import com.apexsoft.monitor.common.http.HttpHelper;
import com.apexsoft.monitor.front.console.app.dao.AppNodeDao;
import com.apexsoft.monitor.front.console.app.om.App;
import com.apexsoft.monitor.front.console.app.om.AppNode;
import com.apexsoft.monitor.front.console.host.om.Host;
import com.apexsoft.monitor.front.console.host.service.HostService;
import com.apexsoft.monitor.front.console.pageModel.PappNode;
import com.apexsoft.monitor.utils.GuavaCacheHelper;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;


@Service("appNodeService")
public class AppNodeService {

	private static final Logger log = LogManager.getRootLogger();

	@Autowired
	@Qualifier("appNodeDao")
	private AppNodeDao appNodeDao = null;

	@Autowired
	@Qualifier("hostService")
	private HostService hostService = null;

	@Autowired
	@Qualifier("appService")
	private AppService appService = null;

	/**
	 * 查询中间件列表
	 * @param pappNode
	 * @return
	 * @throws Exception
	 */
	public JSONObject listByPage(PappNode pappNode) throws Exception {
		//返回查询结果
		JSONObject result = (JSONObject)GuavaCacheHelper.get(MonitorConstant.CACHE_KEY_NODE);//new JSONObject();


//		//将url地址存入list中进行遍历
//		List<String> urlList = new ArrayList<>();
//		if(MonitorThread.hostList!=null && MonitorThread.hostList.size()>0){
//			for(Host host:MonitorThread.hostList){
//				if(host.getHostStatus()==0){
//					continue;
//				}
//				String hostIP = host.getHostIp();
//				String agentPort = host.getAgentPort()+"";
//				if (StringUtils.isNotBlank(hostIP)&&StringUtils.isNotBlank(agentPort)){
//					String url=MonitorConstant.HTTP_Front + hostIP+":"+agentPort+"+/ctrl";
//					urlList.add(url);
//				}
//			}
//		}
//
//		//设置请求头
//		Map<String,String> headerMap = new HashMap<>();
//		headerMap.put("HeaderToken","81CF7DDC68CDF393D3FC705050F71029");
//
//		//入参
//		JSONObject paramsJson = new JSONObject();
//		paramsJson.put("func","Node_List");
//
//
//		JSONArray nodeList = new JSONArray();
//		for (String urlLi : urlList){
//			//调用工具类HttpHelper获取列表数据
//			for(int i=0;i<3;i++){
//				String returnValue =(String)HttpHelper.post(urlLi,paramsJson.toJSONString(),headerMap);
//				JSONObject resultTemo = JSONObject.parseObject(returnValue);
//				if(resultTemo.getIntValue(Result.CODE)>0){
//					List<AppNodeNew> list = new ArrayList<>();
//					JSONArray nodeDatas = resultTemo.getJSONArray("records");
//					for(int j=0;j<nodeDatas.size();j++){
//						JSONObject nodeJson = nodeDatas.getJSONObject(j);
//						AppNodeNew nodeObject = new AppNodeNew(nodeJson);
//						list.add(nodeObject);
//					}
//					nodeList.addAll(list);
//					break;
//				}else{
//					Thread.sleep(500);
//				}
//			}
//		}
//		if(nodeList.size()>0){
//			result.put(Result.CODE, Result.SC_0001);
//			result.put(Result.NOTE, "查询成功");
//			result.put(Result.TOTAL, nodeList.size());
//			result.put(Result.ROWS,nodeList);
//		}else {
//			result.put(Result.CODE, Result.EC_1000);
//			result.put(Result.NOTE, "暂无数据");
//		}
		return result;
	}


	/**
	 * 根据AppCode,获取节点数据
	 * @param appCode
	 * @return
	 * @throws Exception
	 */
	public JSONObject getAllNode(String appCode) throws Exception {
		EntityWrapper<AppNode> entityWrapper = new EntityWrapper<>();
		if (StringUtils.isNotBlank(appCode)){
			entityWrapper.and("app_code={0}", appCode);
		}
		List<AppNode> list = appNodeDao.selectList(entityWrapper);
		return Result.commonListResult(list);
	}

	public JSONArray getAllNodeForComboBoxTree() throws Exception{
		JSONArray array = new JSONArray();
		List<HashMap> appNodeList = appNodeDao.getAllNodeForComboboxTree();
		List<App> appList = appService.getAllAppForList("");
		for(int i=0;i<appList.size();i++){
			JSONObject appObj = new JSONObject();
			appObj.put("id","app_"+appList.get(i).getAppCode());
			appObj.put("text","(应用) "+appList.get(i).getAppName());
			appObj.put("type","app");
			appObj.put("children",getChildern(appNodeList,appList.get(i).getAppCode()));
			array.add(appObj);
		}
		return array;
	}

	private JSONArray getChildern(List<HashMap> appNodeList,String appCode){
		JSONArray array = new JSONArray();
		for(int i=0;i<appNodeList.size();i++){
			HashMap<String,String> map = appNodeList.get(i);
			if(map.get("app_code").equals(appCode)){
				JSONObject jsonObject = new JSONObject();
				jsonObject.put("id",map.get("node_code"));
				jsonObject.put("text","(中间件) "+map.get("node_name"));
				jsonObject.put("type","node");
				jsonObject.put("node_type",map.get("node_type"));
				jsonObject.put("app_code",map.get("app_code"));
				jsonObject.put("app_name",map.get("app_name"));
				jsonObject.put("host_code",map.get("host_code"));
				jsonObject.put("host_name",map.get("host_name"));
				jsonObject.put("host_ip",map.get("host_ip"));
				array.add(jsonObject);
			}
		}
		return array;
	}

	/**
	 * 获取节点对象,包括主机状态,实时日志专用
	 * @param appCode
	 * @return
	 * @throws Exception
	 */
	public JSONObject getAllNodeForLog(String appCode) throws Exception{
		JSONObject result = new JSONObject();
		List<HashMap> list = appNodeDao.getAllNodeForLog(appCode);
		result.put(Result.CODE, Result.SC_0001);
		result.put(Result.NOTE, "查询成功");
		result.put(Result.ROWS, list);
		return result;
	}

	/**
	 * 添加节点
	 * @param request
	 * @return
	 */
	public JSONObject add(HttpServletRequest request){
		JSONObject result = new JSONObject();
		//设置唯一标识
		String nodeCode = UUID.randomUUID().toString();
		String nodeName = request.getParameter("nodeNameTemp");
		String appCode = request.getParameter("appCode");
		String hostCode = request.getParameter("hostCode");
		String servicePort = request.getParameter("servicePort");
		String status = request.getParameter("status");
		String nodeType = request.getParameter("nodeTypeTemp");
		String basePath = request.getParameter("basePath");
		String protocol = request.getParameter("protocol");
		String remark = request.getParameter("remark");
		String dbUser = request.getParameter("dbUser");
		String dbPwd = request.getParameter("dbPwd");
		String dbName = request.getParameter("dbName");
		String urlParams = request.getParameter("url");
		String redisPwd = request.getParameter("redisPwd");
		if (StringUtils.isNotBlank(nodeCode)
				&&StringUtils.isNotBlank(nodeName)
				&& StringUtils.isNotBlank(appCode)
				&& StringUtils.isNotBlank(hostCode)
				&& StringUtils.isNotBlank(status)
				&& StringUtils.isNotBlank(servicePort)
				&& StringUtils.isNotBlank(protocol)
				&& StringUtils.isNotBlank(nodeType)
				) {
			try {
				Host host = hostService.getByCode(hostCode);
				if(host==null || host.getHostStatus()==0){
					result.put(Result.CODE, Result.EC_1000);
					result.put(Result.NOTE, "中间件新增失败【该中间件主机不存在或者未启用】");
					return result;
				}
				//入参
				JSONObject nodeJson = new JSONObject();
				nodeJson.put("node_code",nodeCode);
				nodeJson.put("node_name",nodeName);
				nodeJson.put("node_type",nodeType);
				nodeJson.put("host_code",hostCode);
				nodeJson.put("app_code",appCode);
				nodeJson.put("base_path",basePath);
				nodeJson.put("protocol",protocol);
				nodeJson.put("service_port",Integer.parseInt(servicePort));
				nodeJson.put("status",Integer.parseInt(status));
				nodeJson.put("remark",remark);

				JSONObject dbJson = new JSONObject();
				switch (protocol){
					case "http":
						dbJson.put("url", StringUtils.isBlank(urlParams)?"":urlParams);
						break;
					case "https":
						dbJson.put("url", StringUtils.isBlank(urlParams)?"":urlParams);
						break;
					case "redis":
						dbJson.put("redis_pwd", StringUtils.isBlank(redisPwd)?"":redisPwd);
						break;
					case "mysql":
						dbJson.put("db_name", StringUtils.isBlank(dbName)?"":dbName);
						dbJson.put("db_user", StringUtils.isBlank(dbUser)?"":dbUser);
						dbJson.put("db_pwd",StringUtils.isBlank(dbPwd)?"":dbPwd);
						break;
					case "tcp":
						break;
					default:

				}
				nodeJson.put("attr",dbJson);

				JSONObject paramsJson = new JSONObject();
				paramsJson.put("node",nodeJson);
				paramsJson.put("func","Node_Add");
				//设置请求头
				Map<String,String> headerMap = new HashMap<>();
				headerMap.put("HeaderToken","81CF7DDC68CDF393D3FC705050F71029");
				//获取URL

				String url = MonitorConstant.HTTP_Front + host.getHostIp()+":"+host.getAgentPort()+"/ctrl";
				//调用HttpHelper获取
				for (int i = 0; i <3 ; i++) {
					String returnValue =(String)HttpHelper.post(url,paramsJson.toJSONString(),headerMap);
					JSONObject resultTemo = JSONObject.parseObject(returnValue);
					if (resultTemo.getIntValue("code")>0){
						result.put(Result.CODE, Result.SC_0001);
						result.put(Result.NOTE, "中间件新增成功");
						GuavaCacheHelper.remove(MonitorConstant.CACHE_KEY_NODE);
						break;
					}else {
						result.put(Result.CODE, Result.EC_1000);
						result.put(Result.NOTE, "新增中间件失败");
					}
					Thread.sleep(1000);
				}
			} catch (Exception e) {
				log.error("新增应用失败："+e.getMessage(), e);
				result.put(Result.CODE, Result.EC_1000);
				result.put(Result.NOTE, "新增中间件失败");
			}

		}else {
			result.put(Result.CODE, Result.EC_1000);
			result.put(Result.NOTE, "参数不正确");
		}
		return result;
	}

	/**
	 * 更新中节点
	 * @param request
	 * @return
	 */
	public JSONObject update(HttpServletRequest request) {
		JSONObject result = new JSONObject();
		String nodeCode = request.getParameter("nodeCode");
		String nodeName = request.getParameter("nodeNameTemp");
		String appCode = request.getParameter("appCode");
		String hostCode = request.getParameter("hostCode");
		String servicePort = request.getParameter("servicePort");
		String status = request.getParameter("status");
		String nodeType = request.getParameter("nodeTypeTemp");
		String basePath = request.getParameter("basePath");
		String protocol = request.getParameter("protocol");
		String remark = request.getParameter("remark");
		String dbUser = request.getParameter("dbUser");
		String dbPwd = request.getParameter("dbPwd");
		String dbName = request.getParameter("dbName");
		String urlParams = request.getParameter("url");
		String redisPwd = request.getParameter("redisPwd");

		if (StringUtils.isNotBlank(nodeCode)
				&& StringUtils.isNotBlank(nodeName)
				&& StringUtils.isNotBlank(appCode)
				&& StringUtils.isNotBlank(hostCode)
				&& StringUtils.isNotBlank(status)
				&& StringUtils.isNotBlank(servicePort)
				&& StringUtils.isNotBlank(nodeType)
				&& StringUtils.isNotBlank(protocol)
				) {
			Host host = hostService.getByCode(hostCode);
			if(host==null || host.getHostStatus()==0){
				result.put(Result.CODE, Result.EC_1000);
				result.put(Result.NOTE, "更新记录失败【该中间件主机不存在或者未启用】");
				return result;
			}

			JSONObject nodeJson = new JSONObject();
			nodeJson.put("node_code",nodeCode);
			nodeJson.put("node_name",nodeName);
			nodeJson.put("node_type",nodeType);
			nodeJson.put("host_code",hostCode);
			nodeJson.put("app_code",appCode);
			nodeJson.put("base_path",basePath);
			nodeJson.put("protocol",protocol);
			nodeJson.put("service_port",Integer.parseInt(servicePort));
			nodeJson.put("status",Integer.parseInt(status));
			nodeJson.put("remark",remark);

			JSONObject dbJson = new JSONObject();
			switch (protocol){
				case "http":
					dbJson.put("url", StringUtils.isBlank(urlParams)?"":urlParams);
					break;
				case "https":
					dbJson.put("url", StringUtils.isBlank(urlParams)?"":urlParams);
					break;
				case "redis":
					dbJson.put("redis_pwd", StringUtils.isBlank(redisPwd)?"":redisPwd);
					break;
				case "mysql":
					dbJson.put("db_name", StringUtils.isBlank(dbName)?"":dbName);
					dbJson.put("db_user", StringUtils.isBlank(dbUser)?"":dbUser);
					dbJson.put("db_pwd",StringUtils.isBlank(dbPwd)?"":dbPwd);
					break;
				case "tcp":
					break;
				default:

			}
			nodeJson.put("attr",dbJson);

			JSONObject paramsJson = new JSONObject();
			paramsJson.put("node",nodeJson);
			paramsJson.put("func","Node_Update");
			//请求头
			Map<String,String> headerMap = new HashMap<>();
			headerMap.put("HeaderToken","81CF7DDC68CDF393D3FC705050F71029");
			//获取URL

			String url = MonitorConstant.HTTP_Front + host.getHostIp()+":"+host.getAgentPort()+"/ctrl";
			try {
				for (int i = 0; i <3 ; i++) {
					String returnValue =(String)HttpHelper.post(url,paramsJson.toJSONString(),headerMap);
					JSONObject resultTemo = JSONObject.parseObject(returnValue);
					if (resultTemo.getIntValue("code")>0){
						result.put(Result.CODE, Result.SC_0001);
						result.put(Result.NOTE, "修改成功");
						GuavaCacheHelper.remove(MonitorConstant.CACHE_KEY_NODE);
						break;
					}else {
						result.put(Result.CODE, Result.EC_1000);
						result.put(Result.NOTE, "修改失败");
					}
					Thread.sleep(2000);
				}
			} catch (Exception e) {
				log.error("修改失败："+e.getMessage(), e);
				result.put(Result.CODE, Result.EC_1000);
				result.put(Result.NOTE, "修改失败");
			}
		}else {
			result.put(Result.CODE, Result.EC_1000);
			result.put(Result.NOTE, "参数不正确");
		}
		return result;
	}

	/**
	 * 删除节点
	 * @param nodeCode
	 * @return
	 */
	public JSONObject delete(String nodeCode,String hostCode) {
		JSONObject result = new JSONObject();

		//入参
		JSONObject paramsJson = new JSONObject();
		paramsJson.put("func","Node_Delete");
		paramsJson.put("node_code",nodeCode);
		//获取URL
		Host host = hostService.getByCode(hostCode);
		if(host==null || host.getHostStatus()==0){
			result.put(Result.CODE, Result.EC_1000);
			result.put(Result.NOTE, "删除中间件失败【该中间件主机未启用或者主机不存在】");
			return result;
		}
		String url = MonitorConstant.HTTP_Front + host.getHostIp()+":"+host.getAgentPort()+"/ctrl";
		//设置请求头
		Map<String,String> headerMap = new HashMap<>();
		headerMap.put("HeaderToken","81CF7DDC68CDF393D3FC705050F71029");

		if (StringUtils.isNotBlank(nodeCode)) {

			try {
				for (int i = 0; i <3 ; i++) {
					String returnValue = (String)HttpHelper.post(url,paramsJson.toJSONString(),headerMap);
					JSONObject resultTemo = JSONObject.parseObject(returnValue);
					if (resultTemo.getIntValue(Result.CODE)>0){
						result.put(Result.CODE, Result.SC_0001);
						result.put(Result.NOTE, "删除中间件成功");
						GuavaCacheHelper.remove(MonitorConstant.CACHE_KEY_NODE);
						break;
					}else{
						result.put(Result.CODE, Result.EC_1000);
						result.put(Result.NOTE, "删除中间件失败");
					}
					Thread.sleep(2000);
				}
			} catch (Exception e) {
				log.error("删除中间件失败："+e.getMessage(), e);
				result.put(Result.CODE, Result.EC_1000);
				result.put(Result.NOTE, "删除中间件失败");
			}

		}else {
			result.put(Result.CODE, Result.EC_1000);
			result.put(Result.NOTE, "参数不正确");
		}
		return result;
	}

	public AppNode getById(int id) {
		return appNodeDao.selectById(id);
	}

	public AppNode getByNodeCode(String nodeCode) {
		return appNodeDao.selectByCode(nodeCode);
	}

	/**
	 * 根据主机代码,查询中间件信息
	 * @param hostCode
	 * @return
	 */
	public JSONObject queryNodesByHostCode(String hostCode){
		JSONObject result = new JSONObject();
		try {
			List<AppNode> recodes = appNodeDao.selectByHostCode(hostCode);
			if(recodes!=null && recodes.size()>0){
				result.put(Result.RECORDS,recodes);
				result.put(Result.COUNT,recodes.size());
				result.put(Result.CODE,Result.SC_0001);
				result.put(Result.NOTE,"查询节点成功");
			}else{
				result.put(Result.CODE,Result.EC_1000);
				result.put(Result.NOTE,"查询节点失败");
			}
		} catch (Exception e) {
			log.error("根据主机ID查询节点异常："+e.getMessage(), e);
			result.put(Result.CODE,Result.EC_1000);
			result.put(Result.NOTE, "查询节点异常");
		}
//		Map<String,String> headerMap = new HashMap<>();
//		headerMap.put("HeaderToken","81CF7DDC68CDF393D3FC705050F71029");
//		//入参
//		JSONObject paramsJson = new JSONObject();
//		paramsJson.put("func","Node_Get");
//		paramsJson.put("node_code",hostCode);
//		//获取URL
//		Host host = hostService.getByCode(hostCode);
//		String url = MonitorConstant.HTTP_Front + host.getHostIp()+":"+host.getAgentPort()+"/ctrl";
//		try {
//			String returnValue = (String) HttpHelper.post(url, paramsJson.toJSONString(), headerMap);
//			JSONObject resultTemo = JSONObject.parseObject(returnValue);
//			result.put(Result.CODE, Result.SC_0001);
//			result.put(Result.NOTE, "查询成功");
//			result.put(Result.ROWS, resultTemo.get("object"));
//		}catch (Exception e){
//			log.error("根据主机ID查询节点异常："+e.getMessage(), e);
//			result.put(Result.CODE,Result.EC_1000);
//			result.put(Result.NOTE, "查询节点异常");
//		}
//
		return result;
	}

	public AppNode getByCode(String code){
		return appNodeDao.selectByCode(code);
	}
}
